<template>
  <a-skeleton :loading="loading" active :title="false" :paragraph="{ rows: 6, width: '100%' }">
    <a-card hoverable :bordered="false" size="small">
      <a-table
        size="small"
        :dataSource="dataSource"
        :columns="columns"
        :pagination="false"
        :scroll="{ x: 800 }"
      >
        <template #headerCell="{ column }">
          <template v-if="column.key === 'operation'">
            <div style="display: flex; justify-content: space-between; align-items: center">
              <span> 操作 </span>
              <a-button
                type="primary"
                size="middle"
                @click="addUser"
                v-auth="['admin', 'user:add']"
              >
                新增
              </a-button>
            </div>
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'dept'">
            <span>
              {{ record.dept.name }}
            </span>
          </template>
          <template v-if="column.key === 'enabled'">
            <span>
              <a-switch
                :disabled="user.id === record.id"
                v-model:checked="record.enabled"
                @change="changeEnabled(record, record.enabled)"
              />
            </span>
          </template>
          <template v-if="column.key === 'operation'">
            <span>
              <a-button
                type="link"
                size="middle"
                @click="editUser(record)"
                :disabled="user.id === record.id"
                v-auth="['admin', 'user:edit']"
                >编辑</a-button
              >
              <a-divider type="vertical" />
              <a-popconfirm
                v-if="dataSource.length"
                title="确定删除本条数据吗?"
                @confirm="onDelete(record.id)"
              >
                <a-button
                  type="link"
                  size="middle"
                  :disabled="user.id === record.id"
                  v-auth="['admin', 'user:del']"
                  >删除</a-button
                >
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>
      <!--分页组件-->
      <a-pagination
        style="margin-top: 10px"
        size="small"
        v-model:current="page"
        :total="total"
        show-size-changer
        show-quick-jumper
        :show-total="(total) => `共有 ${total} 条数据`"
        @showSizeChange="onShowSizeChange"
        @change="pageChange"
      />

      <UserModal ref="userModalRef" />
    </a-card>
  </a-skeleton>
</template>
<script lang="ts">
  import { defineComponent, ref, onMounted, watch, createVNode } from 'vue';
  import { Modal, notification } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { useUserStore } from '/@/store/modules/user';
  import DeptFilterTree from './deptFilterTree.vue';
  import UserModal from './userModal.vue';
  import { getUsersApi, editUserApi, delUserApi } from '/@/api/user';
  import { reload, deptTreeNodeId } from './index';

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
      key: 'nickName',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '部门',
      dataIndex: 'dept',
      key: 'dept',
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
    },
    {
      title: '创建日期',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 160,
    },
  ];

  const userStore = useUserStore();

  export default defineComponent({
    components: { DeptFilterTree, UserModal },
    setup() {
      const loading = ref<boolean>(true);
      const dataSource = ref<any>([]);
      const total = ref<number>(0);
      const page = ref<number>(1);
      const pageSize = ref<number>(10);

      const pageChange = (current: number) => {
        page.value = current;
      };

      const onShowSizeChange = (_current: number, size: number) => {
        page.value = 1;
        pageSize.value = size;
      };

      const loadUsers = async (params: object) => {
        try {
          let res = await getUsersApi({
            ...params,
            page: page.value - 1,
            size: pageSize.value,
            sort: 'id,desc',
          });
          dataSource.value = res?.content;
          total.value = res?.totalElements;
        } catch (error) {}
      };

      watch([page, pageSize, reload], () => {
        const params = {};
        if (deptTreeNodeId.value > 0) {
          params['deptId'] = deptTreeNodeId.value;
        }
        loadUsers(params);
      });

      onMounted(() => {
        setTimeout(async () => {
          loading.value = false;
        }, 300);
        loadUsers({});
      });

      const userModalRef = ref();
      const addUser = () => {
        userModalRef.value.open(true, {});
      };
      const editUser = (record) => {
        userModalRef.value.open(false, { ...record });
      };

      const changeEnabled = (data, val) => {
        Modal.confirm({
          title: '提示',
          icon: createVNode(ExclamationCircleOutlined),
          content: '此操作将' + (val ? '启用' : '禁用') + data.username + ', 是否继续？',
          async onOk() {
            try {
              await editUserApi(data);
              notification['success']({
                message: '操作成功!',
                duration: 3,
              });
            } catch (error) {
              data.enabled = !data.enabled;
            }
          },
          onCancel() {
            data.enabled = !data.enabled;
          },
        });
      };

      const onDelete = async (id) => {
        try {
          const ids = [id];
          await delUserApi(ids);

          if (dataSource.value.length == ids.length && page.value > 0) {
            --page.value;
          } else {
            reload.value = !reload.value;
          }
          notification['success']({
            message: '删除成功!',
            duration: 3,
          });
        } catch (error) {}
      };

      const user = userStore.getUser;

      return {
        loading,
        user,
        page,
        total,
        dataSource,
        pageChange,
        onShowSizeChange,
        columns,
        addUser,
        editUser,
        changeEnabled,
        onDelete,
        userModalRef,
      };
    },
  });
</script>
